package com.baseeasy.record;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;


import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.baseeasy.record.play.AudioPlayerActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class AudioRecordActivity extends Activity implements View.OnClickListener {

    private static final String[] PERMISSION_ALL = {
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };
    //申请录音权限
    private static final int GET_RECODE_AUDIO = 1001;
    AudioRecorder audioRecorder;
    private ImageView aliyunBack;
    private ImageView audiorecordRecordBtn;
    private ImageView audiorecordCompleteBtn;
    private TextView tvTime;
    private long mMinDuration = 2;
    private long mMaxDuration = 120;
    private long curPress = 1;
    private Disposable disposable;
    private String filename = "";
    private String mPath = "";
    private boolean needPreview = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_audiorecord);
        verifyPermissions(this);
        mPath = getIntent().getExtras().getString(AudioRecordUtils.EXTRAPATH, "");
        filename = getIntent().getExtras().getString(AudioRecordUtils.EXTRAFILENAME, "");
        needPreview = getIntent().getExtras().getBoolean(AudioRecordUtils.EXTRANEEDPREVIEW, false);
        mMinDuration = getIntent().getExtras().getLong(AudioRecordUtils.EXTRAMIN, 2);
        mMaxDuration = getIntent().getExtras().getLong(AudioRecordUtils.EXTRAMAX, 10);
        audioRecorder = AudioRecorder.getInstance();
        audioRecorder.setContext(this);
        audioRecorder.setRecordpath(mPath);
        audioRecorder.setRecordLister(new AudioRecorder.RecordLister() {
            @Override
            public void onRecordFileComplete(final String path) {
                if (null != AudioRecordUtils.recordLister) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!needPreview) {
                                AudioRecordUtils.recordLister.onRecordFileComplete(path);
                                Intent intent = new Intent();
                                intent.putExtra(AudioRecordUtils.EXTRAPATH, path);
                                setResult(RESULT_OK, intent);
                                finish();
                            } else {
                                Intent intent = new Intent(AudioRecordActivity.this, AudioPlayerActivity.class);
                                intent.putExtra(AudioRecordUtils.EXTRAPATH, path);
                                AudioRecordActivity.this.startActivityForResult(intent, AudioRecordUtils.RECORDCODE);
                            }
                        }
                    });
                }
            }
        });
        initView();
        addListers();
    }

    /**
     * 申请录音权限
     */
    public static void verifyPermissions(Activity activity) {
        boolean permission = (ActivityCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED)
                || (ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
                || (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED);
        if (permission) {
            ActivityCompat.requestPermissions(activity, PERMISSION_ALL,
                    GET_RECODE_AUDIO);
        }
    }

    private void initView() {
        aliyunBack = findViewById(R.id.aliyun_back);
        audiorecordRecordBtn = findViewById(R.id.audiorecord_record_btn);
        audiorecordCompleteBtn = findViewById(R.id.audiorecord_complete_btn);
        tvTime = findViewById(R.id.tv_time);
    }

    private void addListers() {
        aliyunBack.setOnClickListener(this);
        audiorecordRecordBtn.setOnClickListener(this);
        audiorecordCompleteBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.aliyun_back) {
            cancleRecord();
        } else if (id == R.id.audiorecord_record_btn) {
            contrlRecord();
        } else if (id == R.id.audiorecord_complete_btn) {
            stopRecord();
        }
    }

    private void contrlRecord() {
        try {
            if (audioRecorder.getStatus() == AudioRecorder.Status.STATUS_NO_READY) {
                //初始化录音
                if (TextUtils.isEmpty(filename)) {
                    filename = new SimpleDateFormat("yyyyMMddHHmmssSS").format(new Date());
                }
                audioRecorder.createDefaultAudio(filename);
                audioRecorder.startRecord(null);
                curPress = 1;
                setTvTime(curPress, mMaxDuration);
                audiorecordRecordBtn.setImageResource(R.mipmap.audiorecord_icon_record_press);
            } else if (audioRecorder.getStatus() == AudioRecorder.Status.STATUS_START) {
                audiorecordRecordBtn.setImageResource(R.mipmap.audiorecord_icon_record_pause);
                audioRecorder.pauseRecord();
                if (disposable != null && !disposable.isDisposed()) {
                    disposable.dispose();
                }
            } else if (audioRecorder.getStatus() == AudioRecorder.Status.STATUS_PAUSE) {
                audioRecorder.startRecord(null);
                setTvTime(curPress, mMaxDuration);
                audiorecordRecordBtn.setImageResource(R.mipmap.audiorecord_icon_record_press);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void cancleRecord() {
        audioRecorder.canel();
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
        super.onBackPressed();

    }

    private void stopRecord() {
        if (curPress >= mMinDuration) {
            audiorecordCompleteBtn.setImageResource(R.mipmap.audiorecord_icon_complete);
            audiorecordRecordBtn.setImageResource(R.mipmap.audiorecord_icon_record_normal);
//            tvTime.setText("00:00:00");
            audioRecorder.stopRecord();
            if (disposable != null && !disposable.isDisposed()) {
                disposable.dispose();
            }
        }
    }

    @SuppressLint("CheckResult")
    private void setTvTime(long start, long end) {
        disposable = Observable.intervalRange(start, end, 0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        curPress = aLong;
                        tvTime.setText(CalenderUtils.getGapTime(aLong * 1000));
                        if (curPress >= mMinDuration) {
                            audiorecordCompleteBtn.setImageResource(R.mipmap.audiorecord_icon_complete_select);
                        }
                        if (curPress == mMaxDuration) {
                            stopRecord();
                        }
                    }
                });
    }

    @Override
    public void onBackPressed() {
        cancleRecord();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AudioRecordUtils.RECORDCODE && resultCode == RESULT_OK && null != data) {
            String path = data.getExtras().getString(AudioRecordUtils.EXTRAPATH, "");
            int action = data.getExtras().getInt(AudioRecordUtils.EXTRAPREACTION, 1);
            if (AudioRecordUtils.EXTRAPREACTION2 == action) {
                AudioRecordUtils.recordLister.onRecordFileComplete(path);
                Intent intent = new Intent();
                intent.putExtra(AudioRecordUtils.EXTRAPATH, path);
                setResult(RESULT_OK, intent);
                finish();
            } else {
                try {
                    File file=new File(path);
                    if(file.exists()){
                        file.delete();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                Intent intent = new Intent();
                setResult(RESULT_CANCELED, intent);
                finish();
            }
        }
    }
}
